//
//  HJPictureSelectorController.swift
//  zhangmiSinweibo
//
//  Created by zhangmi on 16/5/30.
//  Copyright © 2016年 Paramount Pictures. All rights reserved.
//

import UIKit
import SnapKit
//定义显示图片的信息
private let colCount: CGFloat = 4
private let margin: CGFloat = 3
private let maxImageCount = 4
private let itemWidth: CGFloat = (ScreenWidth - (colCount + 1) * margin) / colCount

//定义可重用的标识
private let PictureCellId = "PictureCellId"

class HJPictureSelectorController: UICollectionViewController {
    
    //定义图片的数组
    lazy var images: [UIImage] = [UIImage]()
    
    //重写构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        //设置itemSize
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        //设置行列的间距
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        //设置每组的内间距
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        
        super.init(collectionViewLayout: layout)
        //注册cell
        self.collectionView?.registerClass(HJPictureSelectorCell.self, forCellWithReuseIdentifier: PictureCellId )
        //设置背景颜色
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()
        


    }
}

//数据源方法 UICollectionViewDataSource
extension HJPictureSelectorController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = images.count == maxImageCount ? 0 : 1
        return images.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //需要 转换类型
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! HJPictureSelectorCell
        cell.backgroundColor = randomColor()
        if indexPath.item == images.count {
            //获取数组中的最后一个数据
            cell.image = nil
            
        }else {
            cell.image = images[indexPath.item]
        }
        
        cell.selectorDelegate = self
        return cell
    }
    
}

//使用分类继承cell的协议
//必选的协议方法, 必须实现
extension HJPictureSelectorController: HJPictureSelectorCellDelegate {
    func userWillAddPicture() {
        print("添加图片")
        //图片选择器是系统的
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
            //如果没有访问权限
            print("没有访问权限")
            return
        }
        
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        //设置图片可以被编辑
        //picker.allowsEditing = true
        
        //使用modal的方式展示图片选择
        self.presentViewController(picker, animated: true, completion: nil)
        
    }
    
//    func userWillDeletePicture() {
    func userWillDeletePicture(cell: HJPictureSelectorCell) {
        print("删除图片")
        //需要知道删除的是哪一张图片
        //1.如何获取点击按钮的所在cell, 协议方法的参数的中获取
        //2.通过cell获取相应的indexPath
        guard let indexPath = collectionView?.indexPathForCell(cell) else {
            return
        }
        //3.需要indexPath 删除数组对应的数据
        images.removeAtIndex(indexPath.item)
        
        //4.操作完数据源之后, 刷新collectionView
        collectionView?.reloadData()
        
    }
}


//遵守图片选择器的协议
extension HJPictureSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //实现图片选择的协议方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        print(editingInfo)
        //保存图片.添加到数组
        images.append(image)
        
        self.collectionView?.reloadData()
        
        //实现协议方法之后, 视图控制器的dismiss就交给了程序员
//        dismissViewControllerAnimated(true) {
//            //完成collectionView 的刷新操作
//            self.collectionView?.reloadData()
    
        dismissViewControllerAnimated(true, completion: nil)
    }
}


//定义协议
@objc protocol HJPictureSelectorCellDelegate: NSObjectProtocol {
    //定义协议方法
    optional func userWillAddPicture()
    
//    optional func userWillDeletePicture()
    
    optional func userWillDeletePicture(cell: HJPictureSelectorCell)
}



class HJPictureSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet{
            //完成给按钮设置的图片
            //隐藏添加按钮, 没有图片的时候, 删除按钮
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    //代理对象的属性 要使用weak, 表示弱引用
    weak var selectorDelegate: HJPictureSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //按钮的点击事件
    @objc private func addBtnDidClick() {
        print(#function)
        if image != nil {
            print("已经添加了图片, 不要再点了")
            return
        }
        selectorDelegate?.userWillAddPicture?()
    }
    
    @objc private func deleteBtnDidClick() {
        print(#function)
        selectorDelegate?.userWillDeletePicture?(self)
    }
    
    //设置界面
    private func setupUI() {
        
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            //make.edges.equalTo(self)
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        //添加按钮的点击事件
        addBtn.addTarget(self, action: #selector(HJPictureSelectorCell.addBtnDidClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(HJPictureSelectorCell.deleteBtnDidClick), forControlEvents: .TouchUpInside)
    }
    
    
    //懒加载控件
    private lazy var addBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_pic_add"), forState: .Normal)
        btn.imageView?.contentMode = .ScaleAspectFill
        //手动设置裁剪父视图
        btn.imageView?.clipsToBounds = true

        return btn
    }()
    
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_photo_close"), forState: .Normal)
        
        return btn
    }()

}

